package com.example.demo.service;


import com.example.demo.dto.LoginRequest;
import com.example.demo.dto.ResetPasswordRequest;
import com.example.demo.entity.AuthLog;
import com.example.demo.entity.User;
import com.example.demo.entity.Admin;
import com.example.mapper.AdminMapper;
import com.example.mapper.AuthLogMapper;
import com.example.mapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class AuthService {
    private static final Logger logger = LoggerFactory.getLogger(AuthService.class);
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private AuthLogMapper authLogMapper;
    private  final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    public boolean login(LoginRequest loginRequest) {
        if("staff".equals(loginRequest.getLoginModel())){
            User user = userMapper.findByJobNum(Integer.valueOf(loginRequest.getAccount()));
            if (user != null && passwordEncoder.matches(loginRequest.getPassword(), user.getUpassword())) {
                return true;
            }
        } else if ("admin".equals(loginRequest.getLoginModel())) {
            Admin admin = adminMapper.findByUaccount(loginRequest.getAccount());
            if(admin != null && passwordEncoder.matches(loginRequest.getPassword(), admin.getUpassword())){
                return true;
            }
        }
        return false;
    }

    public boolean resetPassword(ResetPasswordRequest resetPasswordRequest) {
        User user = userMapper.findByJobNumAndPhone(Integer.valueOf(resetPasswordRequest.getJobNum()), resetPasswordRequest.getPhone());
        return user != null;
    }

    // 用户注册时候调用
    public User registerUser(User user) {
        String encryptedPassword = passwordEncoder.encode(user.getUpassword());
        user.setUpassword(encryptedPassword);
        logger.info("开始注册用户: {}", user);
        int insert = userMapper.insert(user);
        logger.info("用户插入数据库结果: {}", insert);
        return user;
    }
    // 管理员注册的时候调用
    public Admin registerAdmin(Admin admin){
        String encryptedPassword = passwordEncoder.encode(admin.getUpassword());
        admin.setUpassword(encryptedPassword);
        logger.info("开始注册管理员: {}", admin);
        int insert =  adminMapper.insert(admin);
        logger.info("管理员插入数据库结果: {}", insert);
        return admin;
    }
    public List<User> findAllUsers() {
        return  userMapper.findAllUsers();
    }

    public void updateUserSearch(Integer jobNum, Boolean search) {
        logger.info("开始更新用户 {} 的状态为: {}",jobNum, search);
        try{
            User user = userMapper.findByJobNum(jobNum);
            int result = userMapper.updateSearch(jobNum,search);

            AuthLog authLog = new AuthLog();
            authLog.setNum(String.valueOf(jobNum));
            authLog.setName(user.getUname());
            authLog.setPhone(user.getPhone());
            authLog.setSmsTime(new Date());
            authLog.setType(search?"启用":"禁用");
            authLogMapper.insertLog(authLog);

            logger.info("用户更新数据库结果: {}",result);
        }catch (Exception e) {
            logger.error("更新用户 {} 的状态失败:",jobNum, e);
            throw e;
        }
    }
}